package com.childenglish.mapper;

import com.childenglish.entity.FileChunk;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface FileChunkMapper {

    @Insert("INSERT INTO file_chunk (file_md5, file_name, chunk_number, total_chunks, chunk_size, file_size, chunk_path, upload_time, status) " +
            "VALUES (#{fileMd5}, #{fileName}, #{chunkNumber}, #{totalChunks}, #{chunkSize}, #{fileSize}, #{chunkPath}, #{uploadTime}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(FileChunk fileChunk);

    @Update("UPDATE file_chunk SET chunk_path = #{chunkPath}, status = #{status}, upload_time = #{uploadTime} WHERE id = #{id}")
    int update(FileChunk fileChunk);

    @Delete("DELETE FROM file_chunk WHERE file_md5 = #{fileMd5}")
    int deleteByFileMd5(String fileMd5);

    @Delete("DELETE FROM file_chunk WHERE file_md5 = #{fileMd5} AND chunk_number = #{chunkNumber}")
    int deleteByChunkNumber(@Param("fileMd5") String fileMd5, @Param("chunkNumber") Integer chunkNumber);

    @Select("SELECT * FROM file_chunk WHERE file_md5 = #{fileMd5} AND chunk_number = #{chunkNumber}")
    @ResultMap("fileChunkMap")
    FileChunk selectByChunkNumber(@Param("fileMd5") String fileMd5, @Param("chunkNumber") Integer chunkNumber);

    @Select("SELECT * FROM file_chunk WHERE file_md5 = #{fileMd5} ORDER BY chunk_number")
    @Results(id = "fileChunkMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "fileMd5", column = "file_md5"),
            @Result(property = "fileName", column = "file_name"),
            @Result(property = "chunkNumber", column = "chunk_number"),
            @Result(property = "totalChunks", column = "total_chunks"),
            @Result(property = "chunkSize", column = "chunk_size"),
            @Result(property = "fileSize", column = "file_size"),
            @Result(property = "chunkPath", column = "chunk_path"),
            @Result(property = "uploadTime", column = "upload_time"),
            @Result(property = "status", column = "status")
    })
    List<FileChunk> selectByFileMd5(String fileMd5);

    @Select("SELECT COUNT(*) FROM file_chunk WHERE file_md5 = #{fileMd5} AND status = 1")
    int countUploadedChunks(String fileMd5);

    @Select("SELECT DISTINCT file_md5 FROM file_chunk WHERE upload_time < #{expireTime} AND status != 2")
    List<String> selectExpiredChunks(Long expireTime);

    @Update("UPDATE file_chunk SET status = #{status} WHERE file_md5 = #{fileMd5}")
    int updateStatusByFileMd5(@Param("fileMd5") String fileMd5, @Param("status") Integer status);
}